package com.cgtong.android.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.cgtong.android.R;
import com.cgtong.android.adapter.CustomFragmentPagerAdapter;
import com.cgtong.android.base.BaseActivity;
import com.cgtong.android.bean.FilterBean;
import com.cgtong.android.bean.ProblemBean;
import com.cgtong.android.fragment.MyReportsFragment;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.widget.BaseDialog;
import com.cgtong.android.widget.SignCalendar;
import com.cgtong.android.widget.VerticalDrawerLayout;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.EventBus;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.cgtong.android.activity.ProblemDetailActivity.KEY_CODE_REPORT_PROBLEM;
import static com.cgtong.android.activity.ProblemDetailActivity.KEY_LIST_ITEM_ID_POSITION;

/**
 * 我的上报
 * by zhuqingchun
 */
public class MyReportsActivity extends BaseActivity {

    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.view_pager)
    ViewPager mViewPager;
    @BindView(R.id.title_center_txt)
    TextView mTitleCenterTxt;
    @BindView(R.id.title_right_txt)
    TextView mTitleRightTxt;
    @BindView(R.id.title_right_txt1)
    TextView mTitleRightClTxt;
    @BindView(R.id.confirm_img)
    ImageView mConfirmImg;
    @BindView(R.id.cancel_img)
    ImageView mCancelImg;
    @BindView(R.id.drawer_layout)
    VerticalDrawerLayout mDrawerLayout;
    @BindView(R.id.show_begin_time_txt)
    TextView mShowBeginTimeTxt;
    @BindView(R.id.show_end_time_txt)
    TextView mShowEndTimeTxt;
    @BindView(R.id.begin_time_ll)
    LinearLayout mBeginTimeLl;
    @BindView(R.id.end_time_ll)
    LinearLayout mEndTimeLl;

    private String mBeginTime = "";
    private String mEndTime = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_my_reports;
    }

    @Override
    public void initData() {
        mTitleCenterTxt.setText(getString(R.string.txt_title_my_reports));
        mTitleCenterTxt.setCompoundDrawablePadding((int) getResources().getDimension(R.dimen.size_padding_title));
//        mTitleCenterTxt.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.drawable.ic_null_calendar), null);
        mTitleRightTxt.setVisibility(View.VISIBLE);
//        mTitleRightTxt.setText(getString(R.string.txt_recycle_list));
        mTitleRightTxt.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.drawable.ic_trash), null);
        mTitleRightClTxt.setVisibility(View.VISIBLE);
        mTitleRightClTxt.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.drawable.ic_null_calendar), null);
        initViewPager();
    }


    private void initViewPager() {
        final List<Fragment> fragments = new ArrayList<>();
        String[] titleArray = getResources().getStringArray(R.array.my_reports_array);
        fragments.add(MyReportsFragment.newInstance(MyReportsFragment.ALL));//全部
        fragments.add(MyReportsFragment.newInstance(MyReportsFragment.REPORTED));//已上报
        fragments.add(MyReportsFragment.newInstance(MyReportsFragment.TOVOID));//已作废
        fragments.add(MyReportsFragment.newInstance(MyReportsFragment.ACCEPTANCE));//处理中
        fragments.add(MyReportsFragment.newInstance(MyReportsFragment.CLOSE));//已结案
        fragments.add(MyReportsFragment.newInstance(MyReportsFragment.EVALUATE));//已评价
        mViewPager.setAdapter(new CustomFragmentPagerAdapter(getSupportFragmentManager(), fragments, titleArray));
        mViewPager.setOffscreenPageLimit(6);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.setupWithViewPager(mViewPager);
        setUpIndicatorWidth(mTabLayout);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.d("requestCode:" + requestCode + " resultCode:" + resultCode + " data:" + (data != null ? data.toString() : "null"));
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == KEY_CODE_REPORT_PROBLEM) {
            long id = data.getLongExtra(KEY_LIST_ITEM_ID_POSITION, 0);
            if (id != 0) {
                EventBus.getDefault().post(new ProblemBean(id), ConstantManager.DELETE_REPORT_TAG);
            }
        }

    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("我的上报");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("我的上报");
        MobclickAgent.onPause(this);
    }

    /**
     * 日历弹窗
     *
     * @param isBeginTime
     */
    private void showCalendarDialog(final boolean isBeginTime) {
        BaseDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_calendar_dialog)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        final SignCalendar calendar = (SignCalendar) view.findViewById(R.id.calendar);
                        final TextView titleTxt = (TextView) view.findViewById(R.id.tv_title);
                        titleTxt.setText(calendar.getCalendarYear() + "年" + calendar.getCalendarMonth() + "月");
                        calendar.setOnCalendarClickListener(new SignCalendar.OnCalendarClickListener() {
                            @Override
                            public void onCalendarClick(int row, int col, String dateFormat) {
                                LogUtils.d("dateFormat: " + dateFormat);
                                calendar.removeAllMarks();
                                calendar.addMark(dateFormat, 0);
                                if (isBeginTime) {
                                    mBeginTime = dateFormat;
                                } else {
                                    mEndTime = dateFormat;
                                }
                            }
                        });
                        //监听当前月份
                        calendar.setOnCalendarDateChangedListener(new SignCalendar.OnCalendarDateChangedListener() {
                            public void onCalendarDateChanged(int year, int month) {
                                titleTxt.setText(year + "年" + month + "月");
                            }
                        });
                        view.findViewById(R.id.last_month_img).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                calendar.lastMonth();
                            }
                        });
                        view.findViewById(R.id.next_month_img).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                calendar.nextMonth();
                            }
                        });
                        view.findViewById(R.id.confirm_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (!calendar.hasMarks()) {
                                    return;
                                }
                                if (isBeginTime) {
                                    mShowBeginTimeTxt.setText(mBeginTime);
//                                    mBeginTimeTxt.setTextColor(ContextCompat.getColor(MyReportsActivity.this, R.color.color_divider_time));
                                } else {
                                    mShowEndTimeTxt.setText(mEndTime);
//                                    mEndTimeTxt.setTextColor(ContextCompat.getColor(MyReportsActivity.this, R.color.color_divider_time));
                                }
                                dialog.cancel();

                            }
                        });

                        view.findViewById(R.id.cancel_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.BOTTOM)
                .show();
    }

    @OnClick({R.id.title_left_txt, R.id.title_right_txt, R.id.title_right_txt1, R.id.begin_time_ll, R.id.end_time_ll, R.id.confirm_img, R.id.cancel_img, R.id.clear_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_txt:
                finish();
                break;
            case R.id.begin_time_ll:
                showCalendarDialog(true);
                break;
            case R.id.end_time_ll:
                showCalendarDialog(false);
                break;
            case R.id.confirm_img:
                //筛选
                EventBus.getDefault().post(new FilterBean(mBeginTime, mEndTime), ConstantManager.FILTER_TIME_AREA_TAG);
                mDrawerLayout.closeDrawer();
                if(!TextUtils.isEmpty(mBeginTime) || !TextUtils.isEmpty(mEndTime)){
                    mTitleCenterTxt.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.drawable.ic_filter_calendar), null);
                }
                break;
            case R.id.cancel_img:
                mDrawerLayout.closeDrawer();
                break;
            case R.id.title_right_txt:
                this.startActivity(new Intent(this, RecycleListActivity.class));
                break;
            case R.id.title_right_txt1:
                if (mDrawerLayout.isDrawerOpen()) {
                    mDrawerLayout.closeDrawer();
                } else {
                    mDrawerLayout.openDrawerView();
                }
                break;
            case R.id.clear_img:
                mBeginTime = "";
                mEndTime = "";
                mShowBeginTimeTxt.setText(getString(R.string.txt_begin_time_default));
                mShowEndTimeTxt.setText(getString(R.string.txt_end_time_default));
                //清空筛选
                EventBus.getDefault().post(new FilterBean(mBeginTime, mEndTime), ConstantManager.FILTER_TIME_AREA_TAG);
                mDrawerLayout.closeDrawer();
                mTitleCenterTxt.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this, R.drawable.ic_null_calendar), null);

                break;
            default:
                break;
        }
    }


    /**
     * 通过反射修改TabLayout Indicator的宽度（仅在Android 4.2及以上生效）
     */
    public static void setUpIndicatorWidth(TabLayout tabLayout) {
        Class<?> tabLayoutClass = tabLayout.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayoutClass.getDeclaredField("mTabStrip");
            tabStrip.setAccessible(true);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        LinearLayout layout = null;
        try {
            if (tabStrip != null) {
                layout = (LinearLayout) tabStrip.get(tabLayout);
            }
            for (int i = 0; i < layout.getChildCount(); i++) {
                View child = layout.getChildAt(i);
                child.setPadding(0, 0, 0, 0);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    params.setMarginStart(SizeUtils.dp2px(10f));
                    params.setMarginEnd(SizeUtils.dp2px(10f));
                }
                child.setLayoutParams(params);
                child.invalidate();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
